using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEngine;
using static System.Net.Mime.MediaTypeNames;
using Debug = UnityEngine.Debug;
using Application = UnityEngine.Application;

/// <summary>
/// 敌人数据类，实现 ITarget 接口
/// </summary>
public class EnemyData : MonoBehaviour, ITarget
{
    [Header("系统引用")]
    static private EffectSystem effectSystem;

    [Header("基础属性")]
    [SerializeField] private int _currentHP = 100;
    [SerializeField] private int _maxHP = 100;

    [Header("描述")]
    [TextArea(3, 5)]
    public string description;
    // TODO: 可以添加美术资源引用等
    // public Rarity rarity; 
    // public Sprite icon;

    // ITarget 接口实现
    public int currentHP
    {
        get => _currentHP;
        set => _currentHP = Mathf.Clamp(value, 0, maxHP);
    }

    public int maxHP => _maxHP;
    public int Block { get; set; } = 0;
    public int oldHP { get; set; } = 100;

    [Header("敌人特有属性")]
    public int attackPower = 10;
    public string enemyId;
    public string displayName;

    [Header("Buff管理")]
    [SerializeField] private List<Buff> buffs = new List<Buff>();

    // [Header("战斗AI")]
    // public EnemyIntent nextIntent;
    // public List<EnemyBehavior> behaviors = new List<EnemyBehavior>();

    // 事件
    public System.Action<int> OnHPChanged;
    //public System.Action<EnemyIntent> OnIntentChanged;

    // 初始化
    private void Awake()
    {
        effectSystem = FindObjectOfType<EffectSystem>();
        if (effectSystem == null)
        {
            Debug.LogError("EffectSystem not found in scene!");
        }
        if (Application.isPlaying)
        {
            Debug.Log($"[Enemy: {gameObject.name}] 已创建，等待配置初始化");
        }
        // todo：CalculateNextIntent();
    }

    // ITarget 接口实现
    public void AddBuff(Buff buff)
    {
        Buff existingBuff = GetBuff(buff.type);
        if (existingBuff != null)
        {
            existingBuff.stacks += buff.stacks;
        }
        else
        {
            buffs.Add(buff);
        }

        Debug.Log($"[Enemy: {gameObject.name}] 获得 Buff: {buff.type} x{buff.stacks}");
    }

    public Buff GetBuff(BuffType type)
    {
        return buffs.FirstOrDefault(b => b.type == type);
    }
    // 获取所有Buff
    public List<Buff> GetAllBuffs()
    {
        return buffs;
    }
    // 清理过期Buff
    public void RemoveExpiredBuffs()
    {
        List<Buff> expiredBuffs = buffs.Where(b => b.stacks <= 0).ToList();
        foreach(var buff in expiredBuffs)
        {
            buffs.Remove(buff);
            Debug.Log($"[Enemy: {gameObject.name}] 移除过期 Buff: {buff.type}");
        }
    }

    public bool IsAlive()
    {
        return currentHP > 0;
    }

    // 敌人特有方法
    public void PerformAttack(ITarget target)
    {
        Debug.Log($"[Enemy: {gameObject.name}] 攻击 {target}，造成 {attackPower} 点伤害");
        // 这里可以调用 EffectSystem 的 ApplyDamage 方法
    }

    // 回合结束处理
    public void EndTurn()
    {
        // 处理回合结束时的Buff效果
        effectSystem.TriggerAtTurnEnd(this);
    }

    // 重置敌人状态
    public void ResetForCombat()
    {
        currentHP = maxHP;
        Block = 0;
        buffs.Clear();
        //CalculateNextIntent();
        Debug.Log($"[Enemy: {gameObject.name}] 战斗状态已重置");
    }

    // 调试方法
    public void DisplayState()
    {
        Debug.Log($"--- 敌人状态 [{gameObject.name}] ---");
        Debug.Log($"HP: {currentHP}/{maxHP} | Block: {Block} | 攻击力: {attackPower}");
        //Debug.Log($"下一回合意图: {nextIntent.type} - {nextIntent.value}");
        Debug.Log($"Buffs: {string.Join(", ", buffs.Select(b => $"{b.type}x{b.stacks}"))}");
        Debug.Log("-------------------------------");
    }

    void Update()
    {
        if (currentHP != oldHP)
        {
            oldHP = currentHP;
            OnHPChanged?.Invoke(oldHP);
        }
    }
    // 从enemyconfigdata实例化（转换成enemydata方法）
    public void InitializeFromConfig(EnemyConfigData config)
    {
        _maxHP = config.maxHP;
        _currentHP = config.maxHP;
        attackPower = config.attackPower;
        enemyId = config.enemyId;
        displayName = config.displayName;
        description = config.description;

        // 确保 effectSystem 被正确设置（应该在外部统一管理）
        if (effectSystem == null)
        {
            effectSystem = FindObjectOfType<EffectSystem>();
            if (effectSystem == null)
            {
                Debug.LogError("EffectSystem not found in scene!");
            }
        }

        Debug.Log($"[Enemy: {gameObject.name}] 已从配置初始化，HP: {currentHP}/{maxHP}");
    }
}